package com.reader.api.controller.magazine;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.reader.api.controller.BaseController;
import com.reader.api.entity.magazine.MagazineRequest;
import com.reader.api.service.magazine.IReaderMagazineService;
import com.reader.api.utils.CommonFunction;
import com.reader.core.annotation.IgnoreAuth;
import com.reader.core.entity.ResultMessageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description   功能描述
 * @author        jiahaikun
 * @date          2018-11-06
 */
@RestController
@RequestMapping("/api/reader/magazine/")
public class ReaderMagazineController extends BaseController {
private final Logger logger = LoggerFactory.getLogger(ReaderMagazineController.class);

@Autowired
public IReaderMagazineService iReaderMagazineService;


       /**
       *
       * @param magazineRequest
       * @return
       */

       @PostMapping("period/list")
       @ResponseBody
       @IgnoreAuth
       public ResultMessageInfo selectPeriodListPage(@RequestBody MagazineRequest magazineRequest) {
           List<Map<String, Object>> list=iReaderMagazineService.selectPeriodListPage(magazineRequest.getPeriod());
           if(list==null||list.size()<=0){
               return    ResultMessageInfo.ofMessage("查不到数据");
           }
           return ResultMessageInfo.ofSuccess("查询成功！", list);
       }

       @PostMapping("year/list")
       @ResponseBody
       @IgnoreAuth
       public ResultMessageInfo selectYearListPage() {
              List<HashMap<String, Object>> list=iReaderMagazineService.selectYearListPage();

              if(list==null||list.size()<=0){
               return    ResultMessageInfo.ofMessage("查不到数据");
              }

              List<HashMap<String, Object>> yearList = CommonFunction.getGroupList("year","list",list);
              for(int i=0;i<yearList.size();i++){
                     List<HashMap<String, Object>> monthList= (List<HashMap<String, Object>>)yearList.get(i).get("list");
                     monthList= CommonFunction.getGroupList("month","list",monthList);
                     yearList.get(i).put("list",monthList);
              }

              return ResultMessageInfo.ofSuccess("查询成功！", yearList);
       }


       @PostMapping("column/list")
       @ResponseBody
       @IgnoreAuth
       public ResultMessageInfo selectColumnListPage(@RequestBody MagazineRequest magazineRequest) {
          String magazineId=magazineRequest.getMagazineId();
          if(StringUtils.isBlank(magazineId)){
              return    ResultMessageInfo.ofMessage("杂志ID不能为空");
          }
          List<LinkedHashMap<String, Object>> list=iReaderMagazineService.selectColumnListPage(magazineId);

         if(list==null||list.size()<=0){
             return    ResultMessageInfo.ofMessage("查不到数据");
         }

           /**
            * 按杂志ID 分组
            */
           List<LinkedHashMap<String, Object>> magazineList = list.stream()
                   .collect(Collectors.groupingBy(
                                                   q -> q.get("magazineId")+ "_"+q.get("year")+ "_"+q.get("period")+"_"+q.get("number")+  "_"+q.get("price")+ "_"+q.get("lineationPrice")+ "_"+q.get("buy")
                                                  )
                         )
                   .entrySet()
                   .stream()
                   .map(e -> {
                       LinkedHashMap<String, Object> inner = new LinkedHashMap<>();
                       List<LinkedHashMap<String, Object>> newList = e.getValue().stream().map(v -> {
                           v.remove("magazineId");
                           v.remove("year");
                           v.remove("period");
                           v.remove("number");
                           v.remove("price");
                           v.remove("lineationPrice");
                           v.remove("buy");
                           return v;
                       }).collect(Collectors.toList());
                       inner.put("list", newList);
                       String[] temp = e.getKey().split("_");
                       String magazineID = temp[0];
                       String year = temp[1];
                       String period=temp[2];
                       String number=temp[3];
                       Float price = Float.parseFloat(temp[4]);
                       Float lineationPrice = Float.parseFloat(temp[5]);
                       Integer buy =Integer.parseInt(temp[6]);

                       inner.put("magazineId",magazineID);
                       inner.put("year",year);
                       inner.put("period",period);
                       inner.put("number",number);
                       inner.put("price",price);
                       inner.put("lineationPrice",lineationPrice);
                       inner.put("buy",buy);
                       return inner;
                   }).collect(Collectors.toList());

               List<LinkedHashMap<String, Object>> columnResult=   (List<LinkedHashMap<String, Object>>)magazineList.get(0).get("list");

           /**
            * 杂志栏目分组
            */
           List<LinkedHashMap<String, Object>> columnList = columnResult.stream()
                       .collect(Collectors.groupingBy(q -> q.get("columnNum")+"_"+q.get("column")))
                       .entrySet()
                       .stream()
                       .map(e -> {
                           LinkedHashMap<String, Object> inner = new LinkedHashMap<>();
                           List<LinkedHashMap<String, Object>> newList = e.getValue().stream().map(v -> {
                               v.remove("column");
                               v.remove("columnNum");
                               return v;
                           }).collect(Collectors.toList());
                           inner.put("list", newList);
                           String[] temp = e.getKey().split("_");
                           Integer columnNum = Integer.parseInt(temp[0]);
                           String column = temp[1];
                           inner.put("columnNum",columnNum);
                           inner.put("column",column);
                           inner.put("cnt", newList.size());
                           return inner;
                       }).collect(Collectors.toList());


           /**
            * 按栏目columnNum排序
            */

           if(CollectionUtils.isNotEmpty(columnList)){
               Collections.sort(columnList,
                       (Map<String,Object> o1, Map<String,Object> o2) ->(Integer.parseInt(o1.get("columnNum").toString())-Integer.parseInt(o2.get("columnNum").toString()))
               );
           }

           /**
            *
            */
           magazineList.get(0).put("list",columnList);

           return ResultMessageInfo.ofSuccess("查询成功！", magazineList.get(0));
       }

}